
package com.youdianstar.app.ui

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import com.gyf.immersionbar.ImmersionBar
import com.youdianstar.app.R
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.auko.startActivity
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.event.NetStateLiveData
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.network.model.BaseResponse
import com.youdianstar.app.common.util.LogUtil
import com.youdianstar.app.common.util.StrUtil
import com.youdianstar.app.databinding.ActivityDevicePopupBinding
import com.youdianstar.app.entity.NewOrderInfo
import com.youdianstar.app.support.ApiRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

/**
 * 弹宝页面 - 参考iOS BRDevicePopupViewController
 * 功能：检查支付状态 -> 弹出充电宝 -> 获取订单ID -> 显示成功/失败状态
 */
class DevicePopupActivity : BaseActivity<ActivityDevicePopupBinding, ScanViewModel>(), KoinComponent {

    private val apiRepository: ApiRepository by inject()

    private var orderUuid: String = ""
    private var deviceId: String = ""
    private var orderId: String = ""

    // 状态枚举
    private enum class PopupStatus {
        PROCESSING,  // 处理中
        SUCCESS,     // 成功
        FAILED       // 失败
    }

    private var currentStatus: PopupStatus = PopupStatus.PROCESSING

    // 进度条相关
    private var progressHandler: Handler? = null
    private var progressRunnable: Runnable? = null
    private var currentProgress: Float = 0f

    // LiveData
    private val checkPaymentLiveData = NetStateLiveData<Any>()
    private val popupLiveData = NetStateLiveData<Any>()
    private val orderListLiveData = NetStateLiveData<List<NewOrderInfo>>()

    override fun layoutId(): Int = R.layout.activity_device_popup

    override fun initVariableId(): Int = com.youdianstar.app.BR.viewModel

    override fun initViewModel(): ScanViewModel {
        val model: ScanViewModel by viewModel()
        return model
    }

    override fun initData() {
        super.initData()
        ImmersionBar.with(this).statusBarDarkFont(true).init()

        // 获取传递的参数（支持Intent Extra和Deep Link两种方式）
        orderUuid = intent.getStringExtra("orderUuid") ?: ""
        deviceId = intent.getStringExtra(Extra.IT_MSG) ?: ""

        // 如果Intent Extra中没有，尝试从Deep Link URL中获取
        intent.data?.let { uri ->
            if (orderUuid.isEmpty()) {
                orderUuid = uri.getQueryParameter("orderUuid") ?: ""
            }
            if (deviceId.isEmpty()) {
                deviceId = uri.getQueryParameter("deviceId") ?: ""
            }
            LogUtil.d("DevicePopupActivity", "从Deep Link获取参数 - orderUuid: $orderUuid, deviceId: $deviceId")
        }

        LogUtil.d("DevicePopupActivity", "初始化 - orderUuid: $orderUuid, deviceId: $deviceId")

        // 判断是否有orderUuid，如果没有则直接显示创建订单失败
        if (StrUtil.isEmpty(orderUuid)) {
            LogUtil.w("DevicePopupActivity", "orderUuid为空，直接显示创建订单失败")
            showCreateOrderFailedStatus()
            return
        }

        // 有orderUuid，先检查订单状态，再决定是否调用弹出充电宝接口
        showProcessingStatus()
        checkOrderStatus()
    }

    override fun initLiveObserver() {
        super.initLiveObserver()

        // 监听支付状态检查
        checkPaymentLiveData.observe(this) { response: BaseResponse<Any> ->
            LogUtil.d("DevicePopupActivity", "支付状态检查接口返回: code=${response.code}, data=${response.data}")

            // 检查是否有data字段（data存在表示支付成功）
            if (response.data == null) {
                // data为空，说明订单超时或支付失败
                LogUtil.e("DevicePopupActivity", "支付状态检查失败：data为空，订单超时或支付失败")
                showCreateOrderFailedStatus()
                return@observe
            }

            // data存在，说明支付成功，继续调用弹出充电宝接口
            LogUtil.d("DevicePopupActivity", "支付成功，开始调用弹出充电宝接口")
            requestPopup()
        }

        // 监听弹出充电宝接口
        popupLiveData.observe(this) { response: BaseResponse<Any> ->
            LogUtil.d("DevicePopupActivity", "弹出充电宝接口返回: code=${response.code}, msg=${response.message}")

            // 检查业务错误码
            if (response.code != 0 && response.code != 200) {
                // 业务错误码不是0或200，认为是失败
                val errorMsg = response.message ?: "请求失败"
                LogUtil.e("DevicePopupActivity", "业务错误: code=${response.code}, msg=$errorMsg")
                showFailedStatus(errorMsg)
                return@observe
            }

            // 进度条到100%
            currentProgress = 1.0f
            mBinding.progressView.progress = 100
            mBinding.progressLabel.text = "100%"

            // 延迟一点时间显示成功状态，然后调用订单列表接口获取订单ID
            Handler(Looper.getMainLooper()).postDelayed({
                LogUtil.d("DevicePopupActivity", "弹出接口调用成功，调用订单列表接口获取订单ID")
                requestOrderListToGetOrderId()
            }, 500)
        }

        // 监听订单列表接口
        orderListLiveData.observe(this) { response: BaseResponse<List<Any>> ->
            LogUtil.d("DevicePopupActivity", "订单列表接口返回: code=${response.code}, data=${response.data}")

            val orderList = response.data ?: emptyList()

            if (orderList.isNotEmpty()) {
                // 取第一条订单（进行中的订单）
                val firstOrder = orderList[0] as? NewOrderInfo
                val orderId = if (firstOrder != null) {
                    when {
                        firstOrder.id > 0 -> firstOrder.id.toString()
                        !StrUtil.isEmpty(firstOrder.uuid) -> firstOrder.uuid
                        !StrUtil.isEmpty(firstOrder.uuidLastSix) -> firstOrder.uuidLastSix
                        else -> null
                    }
                } else {
                    null
                }

                if (!orderId.isNullOrEmpty()) {
                    LogUtil.d("DevicePopupActivity", "从订单列表获取到订单ID: $orderId")
                    this.orderId = orderId
                    showSuccessStatus(orderId)
                } else {
                    LogUtil.e("DevicePopupActivity", "订单列表中未找到订单ID")
                    showFailedStatus("未找到订单ID")
                }
            } else {
                LogUtil.e("DevicePopupActivity", "订单列表为空，没有进行中的订单")
                showFailedStatus("未找到进行中的订单")
            }
        }
    }

    override fun initClickEvent() {
        // 查看订单按钮（成功时）
        mBinding.viewOrderButton.setOnClickListener {
            if (!StrUtil.isEmpty(orderId)) {
                // 先关闭当前弹充电宝页面，跳转到订单详情
                val intent = startActivity<OrderDetailActivity>(
                    Extra.IT_ORDERNO to orderId,
                    Extra.IT_TYPE to 0
                )
                finish()
                LogUtil.d("DevicePopupActivity", "成功：已关闭弹充电宝页面，跳转到订单详情")
            }
        }

        // 返回按钮（失败时）
        mBinding.backButton.setOnClickListener {
            // 失败时：关闭当前页面并跳转到首页
            navigateToHome()
        }
    }

    /**
     * 显示处理中状态
     */
    private fun showProcessingStatus() {
        currentStatus = PopupStatus.PROCESSING
        mBinding.processingContainer.visibility = View.VISIBLE
        mBinding.successContainer.visibility = View.GONE
        mBinding.failedContainer.visibility = View.GONE

        // 重置进度
        currentProgress = 0f
        mBinding.progressView.progress = 0
        mBinding.progressLabel.text = "0%"

        // 开始进度条动画
        startProgressTimer()
    }

    /**
     * 显示成功状态
     */
    private fun showSuccessStatus(orderId: String) {
        currentStatus = PopupStatus.SUCCESS
        this.orderId = orderId

        LogUtil.d("DevicePopupActivity", "显示成功状态，保存订单ID: $orderId")

        stopProgressTimer()

        // 显示订单ID
        if (!StrUtil.isEmpty(orderId)) {
            mBinding.orderIdLabel.text = "${getString(R.string.order_orderID)}: $orderId"
        } else {
            mBinding.orderIdLabel.text = ""
        }

        mBinding.processingContainer.visibility = View.GONE
        mBinding.successContainer.visibility = View.VISIBLE
        mBinding.failedContainer.visibility = View.GONE
    }

    /**
     * 显示创建订单失败状态（没有orderUuid时）
     */
    private fun showCreateOrderFailedStatus() {
        currentStatus = PopupStatus.FAILED

        stopProgressTimer()

        mBinding.processingContainer.visibility = View.GONE
        mBinding.successContainer.visibility = View.GONE
        mBinding.failedContainer.visibility = View.VISIBLE

        // 设置创建订单失败的提示文字
        mBinding.failedTipLabel.text = getString(R.string.popup_createOrderFailed)
    }

    /**
     * 显示失败状态（租借失败）
     */
    private fun showFailedStatus(message: String?) {
        currentStatus = PopupStatus.FAILED

        stopProgressTimer()

        mBinding.processingContainer.visibility = View.GONE
        mBinding.successContainer.visibility = View.GONE
        mBinding.failedContainer.visibility = View.VISIBLE

        // 如果有后端返回的错误信息，显示错误信息；否则显示默认提示
        mBinding.failedTipLabel.text = if (!message.isNullOrEmpty()) {
            message
        } else {
            getString(R.string.popup_scanAgain)
        }
    }

    /**
     * 开始进度条定时器
     */
    private fun startProgressTimer() {
        stopProgressTimer()

        currentProgress = 0f
        progressHandler = Handler(Looper.getMainLooper())
        progressRunnable = object : Runnable {
            override fun run() {
                // 进度条从0%到90%，然后等待接口返回
                if (currentProgress < 0.9f) {
                    currentProgress += 0.02f // 每次增加2%
                    if (currentProgress > 0.9f) {
                        currentProgress = 0.9f
                    }
                }

                mBinding.progressView.progress = (currentProgress * 100).toInt()
                mBinding.progressLabel.text = "${(currentProgress * 100).toInt()}%"

                progressHandler?.postDelayed(this, 100) // 每100ms更新一次
            }
        }
        progressHandler?.post(progressRunnable!!)
    }

    /**
     * 停止进度条定时器
     */
    private fun stopProgressTimer() {
        progressRunnable?.let {
            progressHandler?.removeCallbacks(it)
            progressRunnable = null
        }
        progressHandler = null
    }

    /**
     * 检查支付状态（先调用此接口，确认支付成功后再调用弹出充电宝接口）
     */
    private fun checkOrderStatus() {
        if (StrUtil.isEmpty(orderUuid)) {
            LogUtil.w("DevicePopupActivity", "orderUuid为空，直接显示创建订单失败")
            showCreateOrderFailedStatus()
            return
        }

        LogUtil.d("DevicePopupActivity", "检查支付状态，orderUuid: $orderUuid")

        CoroutineScope(Dispatchers.IO).launch {
            apiRepository.checkPaymentStatus(orderUuid, checkPaymentLiveData)
        }
    }

    /**
     * 调用弹出充电宝接口
     */
    private fun requestPopup() {
        if (StrUtil.isEmpty(deviceId)) {
            // 不显示错误信息，只显示固定提示
            showFailedStatus(null)
            return
        }

        LogUtil.d("DevicePopupActivity", "调用弹出充电宝接口，deviceId: $deviceId")

        CoroutineScope(Dispatchers.IO).launch {
            apiRepository.rentboxPopup(deviceId, popupLiveData)
        }
    }

    /**
     * 调用订单列表接口获取订单ID（获取进行中的订单，取第一条）
     */
    private fun requestOrderListToGetOrderId() {
        // 使用新接口：POST /sw/app/rentbox/order/list.html/V2
        // status=0 表示进行中的订单
        LogUtil.d("DevicePopupActivity", "调用订单列表接口获取订单ID，status=0（进行中的订单）")

        CoroutineScope(Dispatchers.IO).launch {
            // getNewOrderList内部已经设置了status=0
            apiRepository.getNewOrderList(orderListLiveData)
        }
    }

    /**
     * 跳转到首页（关闭当前页面）
     */
    private fun navigateToHome() {
        LogUtil.d("DevicePopupActivity", "失败：已关闭弹充电宝页面并跳转到首页")
        startActivity<MainActivity>()
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        stopProgressTimer()
    }
}

